import { StrategyEnum } from "@/common/enums/strategy.enum";
import { LoggerService } from "@/common/logger/logger.service";
import { UserService } from "@/modules/user/user.service";
import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { Request } from "express";
import { Strategy } from 'passport-local'


@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, StrategyEnum.LOCAL) {
  constructor(
    private readonly userService: UserService,
    private readonly logger: LoggerService
  ) {
    super({
      usernameField: 'name',
      passwordField: 'password',
      passReqToCallback: true
    })
    this.logger.setContext(LocalStrategy.name)
  }


  async validate(request: Request, name: string, password: string) {
    this.logger.log(`${this.validate.name} was called`);
    this.logger.warn(`name: ${name} password: ${password}`, this.validate.name);
    const user = await this.userService.validateUserByPwd(name, password);
    //如果验证通过 自动会在request上添加user属性
    return user;
  }
}
